<template>
	<el-row style="width: 80%; margin: 0 auto; position: relative; top: 60px">
		<el-col>
			<el-form :inline="true" style="display: flex; justify-content: center; gap: 10px; align-items: center">
				<el-form-item style="flex-shrink: 0; width: 200px">
					<el-input v-model="name" placeholder="输入套装名称" style="width: 100%" @clear="load" />
				</el-form-item>

				<el-form-item style="flex-shrink: 0; width: 180px">
					<el-select v-model="grade" placeholder="选择品级" clearable style="width: 100%" @clear="load">
						<el-option v-for="item in gradeOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item style="flex-shrink: 0">
					<el-button type="primary" :icon="Search" style="min-width: 80px" @click="load"></el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!-- 品级筛选菜单 -->
		<el-col style="margin-bottom: 10px; display: flex; justify-content: center">
			<el-menu :default-active="activeGrade" mode="horizontal" class="category-menu" :ellipsis="false" @select="handleGradeSelect">
				<el-menu-item index="">
					<div class="category-item">
						<span class="category-text">全部品级</span>
					</div>
				</el-menu-item>
				<el-menu-item v-for="item in gradeOptions" :key="item.value" :index="item.value">
					<div class="category-item">
						<span class="grade-icon" :class="`grade-${item.value}`"></span>
						<span class="category-text" :style="{ color: item.color }">
							{{ item.label }}
						</span>
					</div>
				</el-menu-item>
			</el-menu>
		</el-col>

		<!-- 套装网格 -->
		<el-col>
			<el-row :gutter="20" class="suit-grid">
				<el-col v-for="(item, index) in tableData" :key="index" :xs="24" :sm="12" :md="8" :lg="6" :xl="4.8" class="suit-col">
					<el-card shadow="hover" class="suit-card" @click="handleSuitClick(item.id)">
						<div class="suit-header">
							<span class="suit-name">{{ item.name }}</span>
							<el-tag :class="`grade-${item.grade}`" effect="dark" class="grade-tag">
								{{ getGradeLabel(item.grade) }}
							</el-tag>
						</div>

						<div class="suit-properties">
							<el-popover placement="top" trigger="hover">
								<template #reference>
									<el-tag type="info">属性 ({{ item.attribute?.length || 0 }})</el-tag>
								</template>
								<div v-for="(attr, i) in item.attribute" :key="i">
									{{ getAttributeLabel(Object.keys(attr)[0]) }}:
									{{ Object.values(attr)[0] }}
								</div>
							</el-popover>
						</div>

						<div class="suit-effects">
							<el-popover placement="top" trigger="hover">
								<template #reference>
									<el-tag type="success">效果 ({{ item.effect?.length || 0 }})</el-tag>
								</template>
								<div v-for="(eff, i) in sortedEffects(item.effect)" :key="i">拥有{{ eff.piece }}件: {{ eff.description }}</div>
							</el-popover>
						</div>
					</el-card>
				</el-col>
			</el-row>

			<!-- 分页 -->
			<el-col>
				<div class="pagination">
					<el-pagination
						:current-page="pageNum"
						:page-size="pageSize"
						:page-sizes="[10, 20, 30, 50, 100, 500, 1000]"
						size="small"
						layout="total, sizes, prev, pager, next, jumper"
						:total="Number(total)"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div>
			</el-col>
		</el-col>
	</el-row>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { CircleCloseFilled, Delete, Download, Edit, InfoFilled, Operation, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'
import 'md-editor-v3/lib/style.css'
import router from '@/router'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const activeBelong = ref('')
const belong = ref('')
const suitOptions = ref([])
const name = ref('')
const grade = ref('')
const activeGrade = ref('')
const formSize = ref('default')
const ruleFormRef = ref()
const $route = router

const form = reactive({
	id: undefined,
	name: undefined,
	img: undefined,
	aggressivity: 0,
	critical: 0,
	defense: 0,
	mana: 0,
	fire: 0,
	ice: 0,
	drug: 0,
	thunder: 0
})

const attributeMap = {
	aggressivity: '攻击',
	critical: '暴击',
	defense: '防御',
	health: '生命',
	mana: '法力上限',
	physical: '气力上限',
	poison: '毒伤耐性',
	mine: '雷蛰耐性',
	fire: '火焚耐性',
	ice: '寒冻耐性'
}

const gradeOptions = ref([
	{ value: '1', label: '凡品', color: '#5d5c5c' }, // 白色
	{ value: '2', label: '良品', color: '#67C23A' }, // 绿色
	{ value: '3', label: '上品', color: '#409EFF' }, // 蓝色
	{ value: '4', label: '特品', color: '#9A35EF' }, // 紫色
	{ value: '5', label: '仙品', color: '#E6A23C' }, // 金色
	{ value: '6', label: '神珍', color: '#F56C6C' } // 红色
])

const belongOptions = ref([
	{ value: '1', label: '兵器', icon: '/public/picture/兵器.png' },
	{ value: '2', label: '葫芦', icon: '/public/picture/葫芦.png' },
	{ value: '3', label: '头冠', icon: '/public/picture/头冠.png' },
	{ value: '4', label: '臂甲', icon: '/public/picture/臂甲.png' },
	{ value: '5', label: '衣甲', icon: '/public/picture/衣甲.png' },
	{ value: '6', label: '腿甲', icon: '/public/picture/腿甲.png' },
	{ value: '7', label: '珍玩', icon: '/public/picture/珍玩.png' },
	{ value: '8', label: '精魄', icon: '/public/picture/精魄.png' }
])

// 表单校验规则
const rules = reactive({
	name: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],

	img: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	aggressivity: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	critical: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	defense: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	mana: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	fire: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	ice: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	drug: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	thunder: [{ required: true, message: '必选项不能为空', trigger: 'change' }]
})

const getSuitName = id => {
	const suit = suitOptions.value.find(item => item.id === id)
	return suit ? suit.name : '无'
}

const getBelongLabel = value => {
	const item = belongOptions.value.find(item => item.value === value.toString())
	return item ? item.label : '未知类型'
}

const handleSuitClick = async id => {
	$route.push(`/front/equip/equipment/suit/show?id=${id}`)
}

//新增方法
const handleAdd = async () => {
	headerTitle.value = reactive('新增数据')
	dialogVisible.value = true
}
// 修改方法
const handleUpdate = async id => {
	dialogVisible.value = true
	headerTitle.value = reactive('编辑数据')
	const res = await request.get(`/equip/${id}`)
	Object.assign(form, res.data)
}
const handleUpdate1 = async id => {
	$route.push(`/personality?id=${id}`)
}
// 单个删除方法
const handleDel = async id => {
	await request.delete(`/equip/${id}`)
	ElMessage({
		showClose: true,
		message: '删除成功',
		type: 'success'
	})
	await load()
}

// 批量删除方法
const handleBatchDel = async () => {
	const ids = []
	multipleSelection.value.forEach(row => {
		ids.push(row.id)
	})
	$route.push(`/front/equip/detail?id=${ids.toString()}`)
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	const res = await request.get('/suit/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			name: name.value,
			grade: grade.value
		}
	})
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	tableData.value = res.data.records
	total.value = res.data.total
}

// 品级选择处理
const handleGradeSelect = value => {
	grade.value = value
	activeGrade.value = value
	load()
}

// 获取品级标签
const getGradeLabel = value => {
	return gradeOptions.value.find(item => item.value === String(value))?.label || '未知'
}

// 获取属性标签
const getAttributeLabel = key => {
	return attributeMap[key] || key
}

// 排序套装效果
const sortedEffects = effects => {
	return [...effects].sort((a, b) => a.piece - b.piece)
}

// 重置查询
const handleReset = () => {
	name.value = ''
	grade.value = ''
	activeGrade.value = ''
	load()
}

// 分页处理
const handleSizeChange = size => {
	pageSize.value = size
	load()
}

const handleCurrentChange = current => {
	pageNum.value = current
	load()
}

// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 关闭弹框提示方法
const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
		.catch(() => {
			// catch error
		})
}

const handleMenuSelect = index => {
	belong.value = index
	load()
}

// 提交表单校验方法
const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}

	await formEl.validate(async (valid, fields) => {
		if (valid) {
			await request({
				method: form.id ? 'put' : 'post',
				url: form.id ? `/equip/${form.id}` : '/equip',
				data: form
			})
			ElMessage({
				showClose: true,
				message: '操作成功',
				type: 'success'
			})
			await handleResetForm(formEl)
		} else {
			console.log('error submit!', fields)
		}
	})
}
// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/equip/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}
// 批量导出方法
const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request(
		{
			url: `/equip/batch/export/${ids}`,
			method: 'get',
			responseType: 'blob'
		} //在请求中加上这一行，特别重要
	)
	downloadExcel(res, '导出数据表')
}

// 取消弹框方法
const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()

	Object.assign(form, {
		id: undefined,
		name: undefined,
		img: undefined,
		aggressivity: 0,
		critical: 0,
		defense: 0,
		mana: 0,
		fire: 0,
		ice: 0,
		drug: 0,
		thunder: 0
	})
	// formEl.clearValidate("img")
	dialogVisible.value = false
	await load()
}

// 文件上传方法
const uploadimg = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.img = res.data
	ruleFormRef.value.clearValidate('img')
}

// 文件下载
const dowload = async url => {
	window.open(url)
}
// 富文本文件上传
const onUploadImg = async (files, callback) => {
	let i = 0
	const res = await Promise.all(
		files.map(file => {
			if (i > 0) {
				return false
			}
			return new Promise((rev, rej) => {
				const formdata = new FormData()
				formdata.append('file', file)

				request
					.post('/file/upload', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						i++
						rev(res.data)
					})
					.catch(error => rej(error))
			})
		})
	)
	callback(res)
}

load()

onMounted(async () => {
	const res = await request.get('/suit/list')
	suitOptions.value = res.data
})
</script>

<style scoped lang="scss">
.el-form--inline .el-form-item {
	margin-right: 10px;
}

.form_header {
	background-color: #666666;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}
.el-card {
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	border-radius: 8px;
	transition: transform 0.3s ease;

	&:hover {
		transform: scale(1.05);
	}
}

.category-menu {
	border-bottom: 2px solid #f0f0f0;
	padding: 0 20px;
	background: transparent; /* 背景透明 */
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); /* 轻微底部阴影增强层次感 */

	.el-menu-item {
		padding: 0 15px;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		position: relative; /* 用于悬停背景定位 */

		&:before {
			content: '';
			position: absolute;
			bottom: 0;
			left: 50%;
			width: 0;
			height: 2px;
			background-color: #409eff; /* 选中时的底部指示线 */
			transition: width 0.3s ease;
		}

		&:hover {
			background-color: rgba(64, 158, 255, 0.12); /* 悬停半透明背景（比原来明显） */
			transform: translateY(-2px);
			box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15); /* 增强悬停阴影 */

			&:before {
				width: calc(100% - 30px); /* 悬停时显示底部指示线 */
				left: 15px;
			}
		}

		&.is-active {
			.category-text {
				color: #409eff;
				font-weight: 600;
			}
			.el-avatar {
				box-shadow: 0 0 0 2px #409eff;
			}
			&:before {
				width: calc(100% - 30px); /* 选中时固定指示线 */
				left: 15px;
			}
		}
	}
}

.category-item {
	display: flex;
	align-items: center;
	height: 60px; /* 统一菜单项高度 */
	padding: 0 10px;

	.el-avatar {
		margin-right: 8px;
		transition:
			transform 0.3s ease,
			box-shadow 0.3s ease;
	}

	.category-text {
		font-size: 14px;
		color: #333;
		white-space: nowrap; /* 防止文字换行 */
		transition: color 0.3s ease;
	}
}

.category-text {
	margin-top: 5px;
	font-size: 12px;
}

.el-menu-item.is-active .category-text {
	color: var(--el-color-primary);
	font-weight: bold;
}

.suit-card:hover {
	transform: translateY(-3px);
}

.suit-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
	padding-bottom: 12px;
	border-bottom: 1px solid rgba(0, 0, 0, 0.06);

	.suit-name {
		font-size: 16px;
		font-weight: 600;
		color: #2c3e50;
		letter-spacing: 0.5px;
		max-width: 70%;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.grade-tag {
		font-size: 12px;
		border: none;
		border-radius: 12px;
		padding: 4px 10px;
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
	}
}

.suit-name {
	font-size: 16px;
	font-weight: bold;
}

.suit-grade {
	font-size: 12px;
	padding: 4px 8px;
	border-radius: 4px;
	color: white;
}

.grade-1 {
	background-color: #ffffff;
	color: #333;
	border: 1px solid #e4e7ed;
}
.grade-2 {
	background-color: #67c23a;
}
.grade-3 {
	background-color: #409eff;
}
.grade-4 {
	background-color: #9a35ef;
}
.grade-5 {
	background-color: #e6a23c;
}
.grade-6 {
	background-color: #f56c6c;
}

.suit-properties,
.suit-effects {
	margin: 12px 0;

	.el-tag {
		width: 100%;
		justify-content: center;
		padding: 10px 14px;
		border-radius: 8px;
		border: none;
		transition: all 0.2s ease;
		position: relative;
		overflow: visible;

		&::before {
			content: '';
			position: absolute;
			top: -1px;
			left: -1px;
			right: -1px;
			bottom: -1px;
			border-radius: inherit;
			z-index: -1;
			background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), transparent);
		}

		&:hover {
			transform: translateY(-2px);
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
		}
	}
}

.suit-properties .el-tag {
	background: linear-gradient(135deg, #f0f7ff, #e1eeff);
	color: #409eff;

	&::before {
		background: linear-gradient(135deg, rgba(64, 158, 255, 0.1), transparent);
	}
}

.suit-effects .el-tag {
	background: linear-gradient(135deg, #f0fff4, #e1ffe7);
	color: #67c23a;

	&::before {
		background: linear-gradient(135deg, rgba(103, 194, 58, 0.1), transparent);
	}
}

.el-popover div {
	padding: 8px 12px;
	font-size: 13px;
	line-height: 1.6;
	color: #5a5e66;

	&:not(:last-child) {
		border-bottom: 1px solid rgba(0, 0, 0, 0.06);
	}
}

.property-tag,
.effect-tag {
	margin-right: 8px;
	cursor: pointer;
}

.suit-content {
	max-height: 200px;
	overflow: auto;
}

.category-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 0 15px;
}

.grade-icon {
	width: 24px;
	height: 24px;
	border-radius: 50%;
	margin-bottom: 4px;
	border: 1px solid #e4e7ed;
}

.grade-icon.grade-1 {
	background: #ffffff;
	color: #333;
}
.grade-icon.grade-2 {
	background: #67c23a;
}
.grade-icon.grade-3 {
	background: #409eff;
}
.grade-icon.grade-4 {
	background: #9a35ef;
}
.grade-icon.grade-5 {
	background: #e6a23c;
}
.grade-icon.grade-6 {
	background: #f56c6c;
}

.grade-tag {
	padding: 4px 8px;
	border-radius: 4px;
	color: white;
	font-weight: 500;
}

.suit-col {
	padding: 10px;
	flex: 0 0 20%; /* 默认5列 */
	max-width: 20%;

	@media (max-width: 1920px) {
		flex: 0 0 25%; /* 4列 */
		max-width: 25%;
	}

	@media (max-width: 1600px) {
		flex: 0 0 33.3333%; /* 3列 */
		max-width: 33.3333%;
	}

	@media (max-width: 1200px) {
		flex: 0 0 50%; /* 2列 */
		max-width: 50%;
	}

	@media (max-width: 768px) {
		flex: 0 0 100%; /* 1列 */
		max-width: 100%;
	}
}

.suit-card {
	margin: 8px 0;
	border-radius: 8px;
	border: 1px solid rgba(0, 0, 0, 0.08);
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;

	&:hover {
		box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
	}
}

.pagination {
	position: fixed;
	bottom: 20px;
	left: 50%;
	transform: translateX(-50%);
	z-index: 1000;
	background: rgba(255, 255, 255, 0.9);
	padding: 8px 20px;
	border-radius: 24px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	display: inline-flex;

	:deep(.el-pagination__total),
	:deep(.el-pagination__jump),
	:deep(.el-pagination__sizes),
	:deep(.btn-prev),
	:deep(.btn-next) {
		color: #333;
	}

	:deep(.el-pager li) {
		color: #333;

		&.is-active {
			color: #409eff;
		}
	}
}
</style>
